package org.linlinjava.litemall.db.service;

import com.github.pagehelper.PageHelper;
import org.linlinjava.litemall.db.dao.LitemallDistributionMapper;
import org.linlinjava.litemall.db.dao.LitemallIncomeMapper;
import org.linlinjava.litemall.db.dao.LitemallUserMapper;
import org.linlinjava.litemall.db.dao.UserStatisticsMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.util.DateTimeUtils;
import org.linlinjava.litemall.db.vo.IncomeTotalStatistics;
import org.linlinjava.litemall.db.vo.UserWxVo;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Service
public class LitemallUserService {
    @Resource
    private LitemallUserMapper userMapper;

    @Resource
    private LitemallDistributionMapper distributionMapper;

    @Resource
    private UserStatisticsMapper userStatisticsMapper;

    public LitemallUser findById(Integer userId) {
        return userMapper.selectByPrimaryKey(userId);
    }

    public UserVo findUserVoById(Integer userId) {
        LitemallUser user = findById(userId);
        UserVo userVo = new UserVo();
        userVo.setNickname(user.getNickname());
        userVo.setAvatar(user.getAvatar());
        return userVo;
    }

    public LitemallUser queryByOid(String openId) {
        LitemallUserExample example = new LitemallUserExample();
        example.or().andWeixinOpenidEqualTo(openId).andDeletedEqualTo(false);
        return userMapper.selectOneByExample(example);
    }

    public void add(LitemallUser user) {
        user.setAddTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        userMapper.insertSelective(user);
    }

    public int updateById(LitemallUser user) {
        user.setUpdateTime(LocalDateTime.now());
        return userMapper.updateByPrimaryKeySelective(user);
    }

    public List<LitemallUser> querySelective(String username, String mobile, Integer page, Integer size, String sort, String order) {
        LitemallUserExample example = new LitemallUserExample();
        LitemallUserExample.Criteria criteria = example.createCriteria();

        if (!StringUtils.isEmpty(username)) {
            criteria.andUsernameLike("%" + username + "%");
        }
        if (!StringUtils.isEmpty(mobile)) {
            criteria.andMobileEqualTo(mobile);
        }
        criteria.andDeletedEqualTo(false);

        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }

        PageHelper.startPage(page, size);
        return userMapper.selectByExample(example);
    }

    public int count() {
        LitemallUserExample example = new LitemallUserExample();
        example.or().andDeletedEqualTo(false);

        return (int) userMapper.countByExample(example);
    }

    public List<LitemallUser> queryByUsername(String username) {
        LitemallUserExample example = new LitemallUserExample();
        example.or().andUsernameEqualTo(username).andDeletedEqualTo(false);
        return userMapper.selectByExample(example);
    }

    public boolean checkByUsername(String username) {
        LitemallUserExample example = new LitemallUserExample();
        example.or().andUsernameEqualTo(username).andDeletedEqualTo(false);
        return userMapper.countByExample(example) != 0;
    }

    public List<LitemallUser> queryByMobile(String mobile) {
        LitemallUserExample example = new LitemallUserExample();
        example.or().andMobileEqualTo(mobile).andDeletedEqualTo(false);
        return userMapper.selectByExample(example);
    }

    public List<LitemallUser> queryByOpenid(String openid) {
        LitemallUserExample example = new LitemallUserExample();
        example.or().andWeixinOpenidEqualTo(openid).andDeletedEqualTo(false);
        return userMapper.selectByExample(example);
    }

    public void deleteById(Integer id) {
        userMapper.logicalDeleteByPrimaryKey(id);
    }

    /**
     * 用户信息
     * @param userId
     * @return
     */
    public UserWxVo findUserWxVoById(Integer userId) {
        UserWxVo vo = new UserWxVo();
        LitemallUser user = userMapper.selectByPrimaryKey(userId);
        vo.setAvatar(user.getAvatar());
        vo.setGender(user.getGender());
        vo.setHasPayPassword(!StringUtils.isEmpty(user.getPassword()));
        vo.setWithdrawAmount(user.getBalance());
        vo.setUserId(userId);
        vo.setUserLevel(user.getUserLevel());
        vo.setNickname(user.getNickname());


        //推广信息
        LitemallDistributionExample disExample = new LitemallDistributionExample();
        disExample.or().andPromoteIdEqualTo(userId).andTypeEqualTo(1).andDeletedEqualTo(false);
        LitemallDistribution distribution = distributionMapper.selectOneByExample(disExample);

        if(distribution != null){
            Integer inviterId = distribution.getUserId();
            LitemallUser inviterUser = userMapper.selectByPrimaryKey(inviterId);
            vo.setInviterId(inviterId);
            vo.setInviterName(inviterUser.getNickname());
        }

        //累计收益
        List<IncomeTotalStatistics> incomeTotalStatistics = userStatisticsMapper.incomeTotalStatistics(userId);
        if(!CollectionUtils.isEmpty(incomeTotalStatistics)){
            incomeTotalStatistics.forEach(e->{
                if(e.getType() == 1){//直推收益
                    vo.setTotalDirectAmount(e.getPrice());
                }
                if(e.getType() == 2){ //间推收益
                    vo.setTotalIndirectAmount(e.getPrice());
                }
            });
            vo.setTotalAmount(vo.getTotalDirectAmount().add(vo.getTotalIndirectAmount()));//累计收益
        }

        //待入账
        BigDecimal pendingAmount = userStatisticsMapper.pendingAmountStatistics(userId);
        if(pendingAmount != null){
            vo.setPendingAmount(pendingAmount);
        }

        //累计提现
        BigDecimal totalWithdrawAmount = userStatisticsMapper.totalWithdrawAmountStatistics(userId);
        if(pendingAmount != null){
            vo.setTotalWithdrawAmount(totalWithdrawAmount);
        }

        //今日收益
        Date date = new Date();
        Date startTime = DateTimeUtils.beginOfDay(date);
        Date endTime = DateTimeUtils.endOfDay(date);
        List<IncomeTotalStatistics> itodayNcomeTotalStatistics = userStatisticsMapper.todayAmountStatistics(userId,startTime,endTime);
        if(!CollectionUtils.isEmpty(itodayNcomeTotalStatistics)){
            itodayNcomeTotalStatistics.forEach(e->{
                if(e.getType() == 1){//今日直推收益
                    vo.setTodayDirectAmount(e.getPrice());
                }
                if(e.getType() == 2){ //今日间推收益
                    vo.setTodayIndirectAmount(e.getPrice());
                }
            });
        }
        return vo;
    }

    /**
     * 收益列表
     * @param userId
     * @param showType
     * @param page
     * @param limit
     * @return
     */
    public Object findUserPromoteList(Integer userId, Integer showType, Integer page, Integer limit) {

       return null;
    }
}
